package com.mydubbo.core;

import java.util.HashMap;
import java.util.Map;

import com.mydubbo.registry.Registry;
import com.mydubbo.registry.ZookeeperRegistry;
import com.mydubbo.rpc.Server;
import com.mydubbo.rpc.netty.NettyServer;
import com.mydubbo.util.IpUtil;

public class MyDubboServiceStarter {
	
	private Registry registry;
	private Server server;
	private int port;/** 服务启动的端口  **/
	private Map<String, Object> serviceBeanMap = new HashMap<>();
	
	public void addBean(Object obj) {
		Class<?>[] interfaces = obj.getClass().getInterfaces();
		if(interfaces==null || interfaces.length!=1) {
			throw new RuntimeException("对外提供服务的bean需要实现自身接口");
		}
		serviceBeanMap.put(interfaces[0].getName(), obj);
	}
	
	public Object getBean(String className) {
		return serviceBeanMap.get(className);
	}
	
	public void init() {
		if(registry==null) {
			registry = new ZookeeperRegistry();
		}
		if(server==null) {
			server = new NettyServer();
		}
		if(port==0) {
			port = Server.defaultPort;
		}
		server.create(port);
		String ip = IpUtil.getLocalIp();
		for(Map.Entry<String, Object> entry : serviceBeanMap.entrySet()) {
			String className = entry.getKey();
			registry.register(new MyDubboService(className, ip + ":" + port));
		}
	}
	
	public void setRegistry(Registry registry) {
		this.registry = registry;
	}

	public void setServer(Server server) {
		this.server = server;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	private MyDubboServiceStarter() {}
	
	private static class Builder {
		private static MyDubboServiceStarter INSTANCE = new MyDubboServiceStarter();
	}
	
	public static MyDubboServiceStarter getInstance() {
		return Builder.INSTANCE;
	}
}